package com.study.interceptor;

import com.study.pojo.sys.User;
import com.study.service.sys.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//登录拦截
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    //前置方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器");
        //逻辑：判断用户是否登录  本质：判断session中有没有user
        //1、获得session对象并取出user对象
        HttpSession session = request.getSession();
        User user= (User) session.getAttribute("user");

//        未登录跳转到登录界面
        if(user==null){
                response.sendRedirect(request.getContextPath()+"/login/toLogin");
                return false;
        }
        //放行 访问目标资源
        System.out.println("放行");
        return true;
    }

    //后置方法（返回视图之前）
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //完成时方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
